<?php

namespace app\admin\controller;

use think\Db;
use think\Request;

class Wechat extends Base
{
    /**
     * 学校码展示
     * @return mixed|\think\response\Json
     */
    public function schcode(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];
            
            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school|school_name'] = ['like', '%' . $params['school'] . '%'];
            }
            if(isset($params['year']) && $params['year'] != ''){
                $where['year'] = $params['year'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('wechat_school')->alias('ws')
                ->join('school s','ws.school=s.school_erp','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('wechat_school')->alias('ws')
                ->join('school s','ws.school=s.school_erp','LEFT')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('status asc,edittime desc')
                ->field('ws.*,school_name')
                ->select();
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 新建
     * @return mixed|\think\response\Json
     */
    public function activeAdd(){
        if(Request::instance()->isPost()){
            extract(input());
            $insert = [
                'school' => $school,
                'year' => $year,
                'height' => $height,
                'weight' => $weight,
                'send' => $send,
                'addtime' => date('Y-m-d H:i:s'),
                'edittime' => date('Y-m-d H:i:s')
            ];
            $have = Db::table('up_wechat_school')
                ->where('school',$school)
                ->where('year',$year)
                ->where('status',1)
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '此学校当前年份已存在！']);
            }
            $res = Db::table('up_wechat_school')->insert($insert);
            if($res){
                return json(['code' => 200, 'msg' => '新建成功']);
            }else{
                return json(['code' => 100, 'msg' => '新建失败']);
            }
        }
        $school = Db::table('up_school')->where('school_status',1)
            ->field('school_id,school_name,school_erp')->select();
        $this->assign('school',$school);
        $this->assign('year',date('Y'));
        return $this->fetch('wechat/activeadd');
    }

    
    /**
     * 编辑
     * @return mixed|\think\response\Json
     */
    public function activeEdit(){
        $active_id = input('id');
        if(Request::instance()->isPost()){
            extract(input());
            $update = [
                'height' => $height,
                'weight' => $weight,
                'send' => $send,
                'edittime' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_wechat_school')->where('id', $active_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        
        $info = Db::name('wechat_school')->alias('ws')
            ->join('school s','ws.school=s.school_erp','LEFT')
            ->where('id', $active_id)
            ->field('ws.*,school_name')
            ->find();
        $this->assign([
            'id' => $active_id,
            'info' => $info
        ]);
        return $this->fetch('wechat/activeedit');
    }
    /**
     * 改状态（是否开启）
     * @author
     */
    public function changeStatus()
    {
        extract(input());
        if($num == 1){
            $res = Db::table('up_wechat_school')
                ->where('id',$id)
                ->find();
            $have = Db::table('up_wechat_school')
                ->where('school',$res['school'])
                ->where('year',$res['year'])
                ->where('status',1)
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '此学校当前年份已存在！']);
            }
        }
        $res = Db::table('up_wechat_school')
            ->where('id',$id)
            ->update([
                'edittime' => date('Y-m-d H:i:s'),
                'status' => $num
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败']);
        }
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function activeDel(){
        $active_id = input('id');
        $res = Db::table('up_wechat_school')->where('id', $active_id)->delete();
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }

    /**
     * 订单
     * @return mixed|\think\response\Json
     */
    public function order(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];
            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school|orderno|name|phone|schoolerp'] = ['like', '%' . $params['school'] . '%'];
            }
            // 活动名称
            if(isset($params['year']) && $params['year'] != ''){
                $where['year'] = $params['year'];
            }
            // 状态
            if(isset($params['o_status']) && $params['o_status'] != ''){
                $where['send_status'] = $params['o_status'];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('wechat_order')->where($where)->count();// 获取总条数
            $lists = Db::name('wechat_order')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('add_time desc')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function orderdel(){
        $active_id = input('id');
        $res = Db::table('up_wechat_order')->where('o_id', $active_id)->delete();
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    /**
     * 某个订单的物流列表
     * @return mixed|\think\response\Json
     */
    public function see_wuliu(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [
                'w_o_id' => session('wlForOid')
            ];
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('wechat_wuliu')->where($where)->count();// 获取总条数
            $lists = Db::name('wechat_wuliu')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('w_send_time desc')
                ->select();
            if($lists){
                foreach ($lists as $k => $v){
                    $lists[$k]['have'] = '未售后';
                    $have = Db::table('up_wechat_huan')
                        ->where('h_w_id',$v['w_id'])
                        ->find();
                    if($have) $lists[$k]['have'] = '<span style="color: red;">有售后</span>';
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $oid = input('o_id');
        session('wlForOid', $oid);
        return $this->fetch();
    }
    /**
     * 查看物流详情
     * @return mixed|\think\response\Json
     */
    public function seewuliuInfo(){
        $code = input('express_no');
        $info = orderWuLiu($code);
//        dump($info);
        $this->assign('info',$info);
        return $this->fetch('wechat/wuliuinfo');
    }
    /**
     * 售后订单
     * @return mixed|\think\response\Json
     */
    public function huan(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];
            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['h_order_no|orderno|w_express_no|h_express_no'] = ['like', '%' . $params['school'] . '%'];
            }
            // 活动名称
            if(isset($params['school2']) && $params['school2'] != ''){
                $where['schoolerp|school|name'] = ['like', '%' . $params['school2'] . '%'];
            }
            // 状态
            if(isset($params['year']) && $params['year'] != ''){
                $where['year'] = $params['year'];
            }
            // 状态
            if(isset($params['o_status']) && $params['o_status'] != ''){
                $where['h_status'] = $params['o_status'];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_wechat_huan')->alias('wh')
                ->join('up_wechat_order o','wh.h_o_id=o.o_id','LEFT')
                ->join('up_wechat_wuliu w','wh.h_w_id=w.w_id','LEFT')
                ->where($where)->count();// 获取总条数
            $lists = Db::table('up_wechat_huan')->alias('wh')
                ->join('up_wechat_order o','wh.h_o_id=o.o_id','LEFT')
                ->join('up_wechat_wuliu w','wh.h_w_id=w.w_id','LEFT')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('h_add_time desc')
                ->field('wh.*,orderno,school,year,name,size,w_express_no')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    /**
     * 审核
     * @return mixed|\think\response\Json
     */
    public function huanYesNo(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            $tui = Db::table('up_wechat_huan')
                ->where('h_id',$h_id)
                ->field('h_status')
                ->find();
            if($tui['h_status'] != 1){
                return json(['code'=>100,'msg'=>'只有待审核的售后订单才可以审核']);
            }
            $param  = [
                'h_status' => $h_status,
                'h_edit_time'=>$today,
                'h_remark'=>$h_refuse_reason,
            ];
            $res = Db::table('up_wechat_huan')
                ->where('h_id',$h_id)
                ->update($param);
            if($res){
                return json(['code'=>200,'msg'=>'操作成功']);
            }
            return json(['code'=>100,'msg'=>'审核失败，请稍后重试！']);
        }
        $tui = Db::table('up_wechat_huan')
            ->where('h_id',$h_id)
            ->field('h_status')
            ->find();
        if($tui['h_status'] != 1){
            return '只有待审核的售后订单才可以审核！';
            exit();
        }
        return $this->fetch('wechat/huanyesno',['h_id'=>$h_id]);
    }
    /**
     * 导入Excel
     * @return mixed
     */
    public function excelIn(){
        set_time_limit(0);
        if(request()->file('file')){
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            $time = date('Y-m-d H:i:s');
            $data = [];
            for ($i=2;$i<=$highestRow;$i++) {
                $a = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue (); //
                $b = $objPHPExcel->getActiveSheet ()->getCell ("B" . $i)->getValue (); //
                $c = $objPHPExcel->getActiveSheet ()->getCell ("C" . $i)->getValue (); //
                $d = $objPHPExcel->getActiveSheet ()->getCell ("D" . $i)->getValue (); //
                if($a != '' && $c != ''){
                    $oid = Db::table('up_wechat_order')->where('orderno', $a)->value('o_id');
                    $inser = [
                        'w_o_id' => 0,
                        'w_h_id' => 0,
                        'w_express' => $b,
                        'w_express_no' => $c,
                        'w_remark' => $d,
                        'w_type' => 1,
                        'w_send_time' => $time
                    ];
                    if($oid){
                        $inser['w_o_id'] = $oid;
                        Db::table('up_wechat_order')->where('orderno', $a)->update([
                            'send_status' => 2,
                            'edit_time' => $time
                        ]);
                    }
                    $inser2 = [
                        'w_o_id' => $inser['w_o_id'],
                        'w_express_no' => $c,
                        'w_type' => 1
                    ];
                    $have = Db::table('up_wechat_wuliu')->where($inser2)->find();
                    if(empty($have)){
                        $data[] = $inser;
                    }
                }
            }
            if($data){
                $res = Db::table('up_wechat_wuliu')->insertAll($data);
                if($res){
                    echo '/admin/Wechat/order';
                }else{
                    echo '/admin/Wechat/excelIn';
                }
            }else{
                echo '/admin/Wechat/order';
            }
        }
        return $this->fetch('wechat/excelin');
    }
    public function excelOut()
    {
        set_time_limit(0);//防止超时
        $params = input('param.');
        $where = [];

        // 活动名称
        if(isset($params['school']) && $params['school'] != ''){
            $where['school|orderno|name|phone|schoolerp'] = ['like', '%' . $params['school'] . '%'];
        }
        // 活动名称
        if(isset($params['year']) && $params['year'] != ''){
            $where['year'] = $params['year'];
        }
        // 状态
        if(isset($params['o_status']) && $params['o_status'] != ''){
            $where['send_status'] = $params['o_status'];
        }
        $field = [
            'orderno','schoolerp','school', 'year','grade',
            'name','sex','size','height','weight',
            'phone','send_name','send_address','add_time'
        ];
        $data = Db::table('up_wechat_order')
            ->where($where)
            ->order('add_time desc')
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '订单号', '学校标识', '学校名字', '年份', '年级',
                '学生姓名', '性别', '尺码', '身高', '体重',
                '联系电话', '收货人', '收货地址', '提交时间'
            ];
            $status = [];
            $values = [];
            $res = exportExcel('order',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
    /**
     * 导入Excel
     * @return mixed
     */
    public function excelIn2(){
        set_time_limit(0);
        if(request()->file('file')){
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            $time = date('Y-m-d H:i:s');
            $data = [];
            for ($i=2;$i<=$highestRow;$i++) {
                $a = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue (); //
                $b = $objPHPExcel->getActiveSheet ()->getCell ("B" . $i)->getValue (); //
                $c = $objPHPExcel->getActiveSheet ()->getCell ("C" . $i)->getValue (); //
                $d = $objPHPExcel->getActiveSheet ()->getCell ("D" . $i)->getValue (); //
                if($a != '' && $c != ''){
                    $hdata = Db::table('up_wechat_huan')->where('h_order_no', $a)
                        ->field('h_id,h_o_id')->find();
                    $inser = [
                        'w_o_id' => 0,
                        'w_h_id' => 0,
                        'w_express' => $b,
                        'w_express_no' => $c,
                        'w_remark' => $d,
                        'w_type' => 2,
                        'w_send_time' => $time
                    ];
                    if($hdata){
                        $inser['w_o_id'] = $hdata['h_o_id'];
                        $inser['w_h_id'] = $hdata['h_id'];
                        Db::table('up_wechat_huan')->where('h_order_no', $a)->update([
                            'h_status' => 3,
                            'h_send_time' => $time
                        ]);
                    }
                    $inser2 = [
                        'w_o_id' => $inser['w_o_id'],
                        'w_express_no' => $c,
                        'w_type' => 2
                    ];
                    $have = Db::table('up_wechat_wuliu')->where($inser2)->find();
                    if(empty($have)){
                        $data[] = $inser;
                    }
                }
            }
            if($data){
                $res = Db::table('up_wechat_wuliu')->insertAll($data);
                if($res){
                    echo '/admin/Wechat/huan';
                }else{
                    echo '/admin/Wechat/excelIn2';
                }
            }else{
                echo '/admin/Wechat/huan';
            }
        }
        return $this->fetch('wechat/excelin2');
    }
    public function excelOut2()
    {
        set_time_limit(0);//防止超时
        $params = input('param.');
        $where = [];
        // 活动名称
        if(isset($params['school']) && $params['school'] != ''){
            $where['h_order_no|orderno|w_express_no|h_express_no'] = ['like', '%' . $params['school'] . '%'];
        }
        // 活动名称
        if(isset($params['school2']) && $params['school2'] != ''){
            $where['schoolerp|school|name'] = ['like', '%' . $params['school2'] . '%'];
        }
        // 状态
        if(isset($params['year']) && $params['year'] != ''){
            $where['year'] = $params['year'];
        }
        // 状态
        if(isset($params['o_status']) && $params['o_status'] != ''){
            $where['h_status'] = $params['o_status'];
        }
        $field = [
            'h_order_no','orderno','w_express_no','schoolerp','school', 'year','name','size',
            'h_name','h_size','h_num','h_reason','h_remark',
            'h_express','h_express_no','h_add_time','h_status','h_refuse_reason'
        ];
        $data = Db::table('up_wechat_huan')->alias('wh')
            ->join('up_wechat_order o','wh.h_o_id=o.o_id','LEFT')
            ->join('up_wechat_wuliu w','wh.h_w_id=w.w_id','LEFT')
            ->where($where)
            ->order('h_add_time desc')
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '售后单号', '所属订单号', '所属物流号', '学校标识', '学校名称','年份','学生名字','原尺码',
                '商品名称', '调换尺码', '调换数量', '调换原因', '用户备注',
                '寄回物流', '寄回单号', '售后时间', '售后状态', '审核备注'
            ];
            $status = ['h_status'];
            $values = [
                'h_status' => [1 => '待审核',2 => '已同意未发货',3 => '已同意已发货',4 => '已拒绝']
            ];
            $res = exportExcel('orderSale',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}